package com.nowcoder.community.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
@Aspect
public class ServiceLogAspect {
    private static Logger logger =LoggerFactory.getLogger(ServiceLogAspect.class);

    //切点
    @Pointcut("execution(* com.nowcoder.community.service.*.*(..))")
    public void pointcut(){}


    //切点(方法)开始之前织入
    @Before("pointcut()")
    public void before(JoinPoint joinPoint){
        //日志记录示例： 用户[1.2.3.4],在[xxx],访问了[com.nowcoder.community.service.xxx()].
        //获取request，在取得IP地址
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String ip =request.getRemoteHost();
        String now =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        //获取包名+类名
        String target=joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName();
        logger.info(String.format("用户[%s],在[%s],访问了[%s]",ip,now,target));
    }
    //切点(方法)开始之后织入
//    @After("pointcut()")
//    public void after(){}

    //有返回值之后织入
//    @AfterReturning("pointcut()")
//    public void afterReturning(){}

    //在抛出异常的时候织入
//    @AfterThrowing("pointcut()")
//    public void afterThrowing(){}

    //在 前  切点  后  织入
//    @Around("pointcut()")
//    public void around(){}
}
